// index.js
const request = require("miniapp-request");
const store = require('../../libs/storage');
const app = getApp();

global.Page({
    data: {
        shareMessage: '邀请您参加肿瘤防治健康跑',
        showFirstLoading: true,
        isFirstLoad: true,
        region: '请选择', //我的省市区
        letters: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"],
        qaList: [],
        qaListIndex: 0,
        regionIndex: 0,
        regionIndexNext: 0,
        finishedCgt: '',
        finishedKpt: '',
        // 提交后如果有错，就显示正确答案
        showRightAnswer: false,
        showRightAnswerIndex: 0,
        showGuideMsg: false,
        regionPicker: ['四川省', '成都市', '']
    },
    onShareAppMessage: function (res) {
        return {
            title: this.data.shareMessage || this.data.title,
            path: '/pages/index/index'
        }
    },
    onLoad: function (options) {
        if (options.regionIndex) {
            // 地图页面点击气球过来的
            this.setData({
                qaListIndex: 1,
                regionIndex: options.regionIndex,
                finishedCgt: options.finishedCgt,
                finishedKpt: options.finishedKpt
            })
        }
        // 取得题目列表
        this.getQaList();
    },
    // 取得题目列表
    getQaList() {
        let {
            isFirstLoad,
            loading,
            showFirstLoading,
            qaListIndex,
            regionIndex
        } = this.data

        wx.showNavigationBarLoading();

        const data = {}

        if (!showFirstLoading) {
            isFirstLoad && wx.showLoading()
        }
        isFirstLoad || this.setData({
            loading: true
        })

        request({
            url: '/index/Qa/qaList.html',
            data
        }).then(res => {
            wx.hideLoading({
                noConflict: true,
                success: () => {
                    this.setData({
                        isFirstLoad: false
                    })
                }
            })
            const {
                code,
                msg,
                data
            } = res.data
            loading = false
            if (code >= 0) {
                if (qaListIndex == 1) {
                    // 地图页面点击气球进来的
                    let regionIndexNext = data.regionIndex;
                    if (data.qaListIndex > qaListIndex) {
                        // 题已经做完
                        regionIndexNext = data.qaList[qaListIndex]['region'].length;
                    }
                    this.setData({
                        qaList: data.qaList,
                        regionIndexNext: regionIndexNext,
                        showRightAnswer: regionIndex < regionIndexNext ? true : false,
                    });
                } else {
                    this.setData({
                        qaList: data.qaList,
                        qaListIndex: data.qaListIndex,
                        regionIndex: data.regionIndex,
                        regionIndexNext: data.regionIndex,
                        showRightAnswer: false,
                    });
                }
                this.setData({
                    loading,
                    showFirstLoading: false
                });
                this.judgeShowGuideMsg();
            } else {
                this.setData({
                    showFirstLoading: false
                });
                wx.showModal({
                    title: '提示',
                    content: msg,
                    showCancel: false,
                    complete(res) {
                        wx.switchTab({
                            url: '/pages/startTest/startTest'
                        })
                    }
                });
            }
            wx.stopPullDownRefresh()
            wx.hideNavigationBarLoading()
        }).catch(e => {
            this.setData({
                loading: false,
                countError: true,
                showFirstLoading: false
            })
            wx.stopPullDownRefresh();
            wx.hideNavigationBarLoading();
            wx.hideLoading({
                noConflict: true
            });
            wx.showToast({
                title: '网络异常，提交回答失败，请稍后再试。',
                duration: 1000,
                icon: 'none'
            })
        })
    },
    // 选项被点击
    onItemSelected(e) {
        console.log(e);
        let qa_bank_idx = e.currentTarget.dataset.qa_bank_idx;
        let select_idx = e.currentTarget.dataset.select_idx;
        let {
            qaList,
            qaListIndex,
            regionIndex,
            regionIndexNext,
            showRightAnswer
        } = this.data;
        if (regionIndex != regionIndexNext || showRightAnswer) {
            // 回看或者已提交后不能修改
            wx.showToast({
                title: '已提交的答案，不能修改哦',
                icon: 'none',
                duration: 4000
            });
            return;
        }
        var qa_bank = qaList[qaListIndex]['region'][regionIndex]['qa_bank'][qa_bank_idx];
        console.log(qa_bank);

        if (qa_bank.classify == '基本情况' &&
            (qa_bank.q_no == '03' ||
                qa_bank.q_no == '04' ||
                qa_bank.q_no == '05' ||
                qa_bank.q_no == '06'
            )
        ) {
            // 基本情况：您的民族
            select_idx = e.detail.value;
            console.log("下拉选择：" + select_idx);
            qa_bank.my_answer = qa_bank.select_list[select_idx].text;
        }

        if (qa_bank.classify == '基本情况' && qa_bank.q_no == '07') {
            // 基本情况：省市区选择
            // 选择常住地
            qa_bank.my_answer = e.detail.value;
            console.log(qa_bank.my_answer);
        } else {
            let old_is_selected = qa_bank.select_list[select_idx].is_selected;
            console.log(old_is_selected);
            // 如果是单选题，先清除原来的选择
            if (qa_bank['type_tag'] == '单选') {
                for (let i = 0; i < qa_bank.select_list.length; i++) {
                    qa_bank.select_list[i].is_selected = 'no';
                }
            }

            if (old_is_selected == 'yes') {
                // 取消选择
                qa_bank.select_list[select_idx].is_selected = 'no';
            } else {
                // 选择
                qa_bank.select_list[select_idx].is_selected = 'yes';

                // 多选题
                if (qa_bank['type_tag'] == '多选') {
                    if (qa_bank.select_list[select_idx].text == "不知道") {
                        // 选择了不知道 就取消其他选择
                        for (let i = 0; i < qa_bank.select_list.length; i++) {
                            if (i != select_idx) {
                                qa_bank.select_list[i].is_selected = 'no';
                            }
                        }
                    } else {
                        // 选择其他选择，就取消选择不知道
                        for (let i = 0; i < qa_bank.select_list.length; i++) {
                            if (qa_bank.select_list[i].text == "不知道") {
                                qa_bank.select_list[i].is_selected = 'no';
                            }
                        }
                    }
                }
            }
        }

        qaList[qaListIndex]['region'][regionIndex]['qa_bank'][qa_bank_idx] = qa_bank;
        this.setData({
            qaList: qaList,
        });
    },
    // 闯关题回看
    lookBack(e) {
        let region_idx = e.currentTarget.dataset.region_idx;
        let {
            regionIndex,
            regionIndexNext
        } = this.data;
        if (regionIndexNext == 0 || region_idx == regionIndex) {
            // 本来就在第一个或者点击当前市州
            return;
        } else if (region_idx <= regionIndexNext) {
            if (regionIndex == regionIndexNext) {
                // 正在答题的页面回看
                var that = this;
                wx.showModal({
                    content: '您已跑完' + regionIndexNext + '/21个市（州），坚持就是胜利，继续前进，不要放弃哟',
                    cancelText: '依然返回',
                    confirmText: '继续答题',
                    success(res) {
                        if (res.confirm) {
                            console.log('用户点击确定');
                        } else if (res.cancel) {
                            console.log('用户点击取消');
                            that.setData({
                                regionIndex: region_idx,
                                showRightAnswer: region_idx < regionIndexNext ? true : false
                            });
                            wx.pageScrollTo({
                                scrollTop: 0
                            });
                        }
                    }
                });
            } else {
                // 回看页面再跳转
                this.setData({
                    regionIndex: region_idx,
                    showRightAnswer: region_idx < regionIndexNext ? true : false
                });
                wx.pageScrollTo({
                    scrollTop: 0
                });
            }
        } else {
            wx.showToast({
                title: '请按顺序答题，不能跳过',
                icon: 'none',
                duration: 4000
            });
        }
    },
    // 下一个市州
    toNext() {
        let {
            letters,
            qaList,
            qaListIndex,
            regionIndex,
            showRightAnswer
        } = this.data;
        if (showRightAnswer) {
            // 显示答案后直接提交答题
            this.setData({
                showRightAnswer: false
            });
            this.toCommitMyAs();
            return;
        }
        var region = qaList[qaListIndex]['region'][regionIndex];

        console.log(region);
        // var showRightAnswer = [];
        showRightAnswer = false;
        // 判断全部题是否都已回答
        for (let index = 0; index < region.qa_bank.length; index++) {
            var selectedCount = 0;
            var qa_bank = region.qa_bank[index];

            var is_right = 'yes';
            var right_answer = [];
            for (let j = 0; j < qa_bank['select_list'].length; j++) {
                let select = qa_bank['select_list'][j];
                if (select['is_selected'] == 'yes') {
                    selectedCount++;
                    // 闯关题判断对错
                    if (qa_bank['classify'] == "闯关题") {
                        // 判断是否选择了错误的答案
                        if (select['score'] == '0') {
                            // 选择了错误的答案
                            is_right = 'no';
                        }
                    }
                } else if (select['score'] > 0 && qa_bank['classify'] == "闯关题") {
                    // 正确的答案没有选
                    is_right = 'no';
                }

                // 记录正确答案
                if (select['score'] !== '0') {
                    right_answer.push(letters[j]);
                }
            }
            qa_bank['is_right'] = is_right;
            qa_bank['right_answer'] = right_answer.join('、');

            if (qa_bank.classify == '基本情况' && qa_bank.q_no == '07' && qa_bank.my_answer != '') {
                // 选择常住地
                selectedCount++;
            }

            if (selectedCount == 0) {
                console.log(qa_bank);
                wx.showModal({
                    title: qa_bank.q_no + '题还没有做哦',
                    content: "做完再提交吧",
                    showCancel: false,
                });
                return;
            }
            if (is_right == 'no') {
                // 选择错误，添加到显示解析列表
                showRightAnswer = true;
            }
        }
        this.setData({
            qaList,
        });
        if (showRightAnswer) {
            wx.pageScrollTo({
                scrollTop: 0
            });
            this.setData({
                showRightAnswer,
            });
            return
        } else {
            if (qaListIndex == 1) {
                // 闯关题才显示
                wx.showToast({
                    title: '恭喜全对',
                    duration: 800,
                    icon: 'success',
                });
            }
            // 提交答题
            this.toCommitMyAs();
        }
    },
    // 判断是否显示引导语
    judgeShowGuideMsg() {
        let {
            qaListIndex,
            regionIndex,
            regionIndexNext
        } = this.data;
        if (regionIndex == regionIndexNext) {
            // 不是回看才显示引导语
            if (regionIndex == 0) {
                this.setData({
                    showGuideMsg: true
                });
            }
        }
    },
    // 关闭引导语对话框
    closeGuideDialog(e) {
        console.log("关闭引导语对话框");
        this.setData({
            showGuideMsg: false
        });
    },
    // 关闭正确答案对话框
    hideRightAnswer(e) {
        console.log("关闭正确答案对话框");
        this.setData({
            showRightAnswer: false
        });
    },
    // 提交我的回答
    toCommitMyAs() {
        let {
            qaList,
            qaListIndex,
            regionIndex,
            regionIndexNext,
            loading
        } = this.data;

        if (loading) {
            // 已经在提交中
            return;
        }
        var region = qaList[qaListIndex]['region'][regionIndex];

        this.setData({
            loading: true
        });
        console.log("==============================/index/Qa/myAs.html");
        request({
            url: '/index/Qa/myAs.html',
            data: {
                region: region
            },
            method: 'POST'
        }).then(res => {
            wx.hideLoading({
                noConflict: true
            });
            const {
                code,
                msg,
                data
            } = res.data
            this.setData({
                loading: false
            });
            if (code >= 0) {
                // 判断下一步
                if (regionIndex + 1 < qaList[qaListIndex]['region'].length) {
                    // 市州还未完
                    regionIndex++;
                } else if (qaListIndex + 1 < qaList.length) {
                    // 题型还未完
                    qaListIndex++;
                    regionIndex = 0;
                } else {
                    // 全部答完了：跳转到结果页面
                    wx.redirectTo({
                        url: '/pages/result/result'
                    });
                    return;
                }

                wx.pageScrollTo({
                    scrollTop: 0
                });
                this.setData({
                    qaListIndex,
                    regionIndex,
                    regionIndexNext: regionIndex,
                });

                this.judgeShowGuideMsg();
            } else {
                wx.showModal({
                    title: '提示',
                    content: msg,
                    showCancel: false,
                });
            }
        }).catch(e => {
            wx.showToast({
                title: '网络异常，提交回答失败，请稍后再试。',
                duration: 1000,
                icon: 'none'
            })
        })
    }
})